package com.haima.sage.bigdata.api.frame.filter.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.haima.sage.bigdata.api.frame.filter.FilterService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.util.Map;

public class JsonFilterService extends FilterService<JsonFilter> {
    private static final Logger LOG = LogManager.getLogger(JsonFilterService.class);

    private ObjectMapper mapper;

    public JsonFilterService(JsonFilter filter) {
        super(filter);
        if (filter.getFields() == null) {
            throw new IllegalArgumentException("json filter fields empty");
        }
        this.mapper = new ObjectMapper();
    }

    @Override
    public Map<String, Object> deal(Map<String, Object> map) {
        if (this.filter.getFields() != null) {
            for (String field : this.filter.getFields()) {
                Object obj = map.get(field);
                if (obj instanceof String) {
                    try {
                        Map<?, ?> dist = mapper.readValue(obj.toString(), Map.class);
                        map.put(field, dist);
                    } catch (IOException e) {
                        LOG.debug("json filter error", e);
                    }
                }
            }
        }
        return map;
    }
}
